/**
 * 
 */
package com.kpmg.questionnaire.interceptor;

import com.kpmg.questionnaire.model.UserEntity;
import com.kpmg.questionnaire.utils.WebConstants;
import com.kpmg.questionnaire.utils.WebUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Hanks
 *
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

	@SuppressWarnings("null")
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		UserEntity currentUser = WebUtils.getSessionObject(request, UserEntity.class, WebConstants.SESSION_USER_KEY);
		if(null == currentUser){
			WebUtils.responseHtml(response,
					"<script type=\"text/javascript\">(window.parent||window).location.href = \""
							+ request.getContextPath() + "/login\";</script>");
			return false;
		}else{
//			已登陆

			if(!(currentUser.getType().equalsIgnoreCase("admin"))){
				String uri = request.getRequestURI();
				String [] stringArr= uri.split("/");


				if( stringArr.length >2  && stringArr[2].equalsIgnoreCase("question")){

					if( stringArr.length >3  && stringArr[3].equalsIgnoreCase("list")){
						if(stringArr.length >4){

						}else{
							WebUtils.responseHtml(response,
									"<script type=\"text/javascript\">(window.parent||window).location.href = \""
											+ request.getContextPath() + "/login\";</script>");
							return false;
						}

					}else{
						WebUtils.responseHtml(response,
								"<script type=\"text/javascript\">(window.parent||window).location.href = \""
										+ request.getContextPath() + "/login\";</script>");
						return false;
					}



				}else if(stringArr.length >2 && stringArr[2].equalsIgnoreCase("answerConfirm")){

				}else if(stringArr.length >2 && stringArr[2].equalsIgnoreCase("answer")){

				}else if(stringArr.length >2 && stringArr[2].equalsIgnoreCase("results")){

				}else if(stringArr.length>2 && stringArr[2].equalsIgnoreCase("html") ){

				}else {
					WebUtils.responseHtml(response,
							"<script type=\"text/javascript\">(window.parent||window).location.href = \""
									+ request.getContextPath() + "/login\";</script>");
					return false;
				}

//				if("/question".equalsIgnoreCase(uri)){
//					WebUtils.responseHtml(response,
//							"<script type=\"text/javascript\">(window.parent||window).location.href = \""
//									+ request.getContextPath() + "/login\";</script>");
//					return false;
//				}

			}else{

			}
		}
		return super.preHandle(request, response, handler);
	}

}
